from PySide6.QtWidgets import QDialog
from sqlalchemy.orm import Session
from views.initsetting.initsetting import Ui_initsetting
from settings.publicvar import engine
from views.initsetting.mode.initsetting import InitSetting
from views.schoolInfo.model.SchoolInfo import SchoolInfo


class InitSettingView(QDialog,Ui_initsetting):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setFormStructure()
        self.is_state()
        self.savebtn.clicked.connect(self.saveFun)
        self.changebtn.clicked.connect(self.changeFun)
        self.resetbtn.clicked.connect(self.resetFun)

    def setFormStructure(self):
        with Session(engine) as session,session.begin():
            schools = session.query(SchoolInfo).all()
            for school in schools:
                self.schoolinfo.addItem(str(school.id) + "-" + school.name)
            try:
                initsetting = session.query(InitSetting).one()
                self.idx.setText(str(initsetting.id))
                self.name.setText(initsetting.name)
                self.schoolinfo.setCurrentText(str(initsetting.school.id)+"-"+initsetting.school.name)
            except:
                self.idx.setText('')

    def is_state(self):
        with Session(engine) as session,session.begin():
            initsetting = session.query(InitSetting).first()
            if not initsetting:
                self.changebtn.hide()
            else:
                self.savebtn.hide()

    def saveFun(self):
        idx = self.idx.text()
        name = self.name.text()
        school = self.schoolinfo.currentText()
        school_id = school.split('-')[0]
        with Session(engine) as session, session.begin():
            session.query(InitSetting).all()
            initsetting = InitSetting(name=name,school_id=school_id)
            session.add(initsetting)

    def changeFun(self):
        idx = self.idx.text()
        name = self.name.text()
        school = self.schoolinfo.currentText()
        school_id = school.split('-')[0]
        with Session(engine) as session, session.begin():
            session.query(InitSetting).filter(InitSetting.id==idx).update({'name':name,'school_id':school_id})

    def resetFun(self):
        self.name.setText('')
        self.schoolinfo.setCurrentText('')